<template>
  <div :class="`target ${isBorder && 'border'}`" ref="target">
    grandparent: {{ data }}
    <div v-if="isAdd" class="target-son">target-son add</div>

    <div :class="`target-son ${isBorder && 'border'}`">
      parent: {{ data }}
      <div v-if="isAdd" class="target-child">grandson add</div>
      <div :class="`target-child ${isBorder && 'border'}`">
        grandson: {{ data }}
      </div>
    </div>
  </div>
  <el-button @click="changeBorder" type="primary">change border</el-button>
  <el-button @click="changeData" type="primary">change data</el-button>
  <el-button @click="addNode" type="primary">add node</el-button>
  <el-button @click="() => (console.log(takeRecords()), stop())" type="danger"
    >Stop</el-button
  >

  <div>杨艺</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { useMutationObserver } from '@vueuse/core';
const target = ref(null);
const data = ref('data');
const isAdd = ref(false);
const isBorder = ref(false);

//
const { stop, takeRecords } = useMutationObserver(
  target,
  (mutations) => {
    console.log(mutations);
  },
  //attributes/characterData/childList 至少一个为true
  {
    //监听属性改变  attributes/attributeFilter/attributeOldValue 一个不填为false,并且符合逻辑
    attributes: true,
    // attributeFilter: ['class'],
    // attributeOldValue: true,

    //是否监听后代变化 可填
    subtree: true,
    // characterData/characterDataOldValue 有一个为true 则为true characterData>characterDataOldValue
    characterData: true,
    characterDataOldValue: false,

    // 监听子组件的删除增加(若subtree为false,则孙代无效)
    childList: true,
  }
);

const changeBorder = () => {
  isBorder.value = true;
};
const changeData = () => {
  data.value = 'change data';
};
const addNode = () => {
  isAdd.value = !isAdd.value;
};
</script>
<style>
.target {
  overflow-y: auto;
  border: 1px dotted salmon;
  margin: 10px;
  &.border {
    border: 1px solid salmon;
  }
}
.target-son {
  margin: 10px;
  border: 1px dotted seagreen;
  &.border {
    border: 1px solid seagreen;
  }
}
.target-child {
  margin: 20px;
  padding: 10px;
  border: 1px dotted slateblue;
  &.border {
    border: 1px solid slateblue;
  }
}
</style>
